<script setup>
import pageConrtainer from '@/components/pageConrtainer.vue'
import { ref, onMounted } from 'vue'
import { Edit, Delete } from '@element-plus/icons-vue'
import selectCategory from '@/components/selectCategory.vue'
import {
  getArticleListAPI,
  getArticleCatagoryAPI,
  addArticleAPI,
  getArticleDetailAPI,
  editArticleAPI,
  deleteArticleAPI
} from '@/api/article'
import dayjs from 'dayjs'
import Upload from '@/components/upload.vue'
import { QuillEditor } from '@vueup/vue-quill'
import '@vueup/vue-quill/dist/vue-quill.snow.css'
import axios from 'axios'

// 文章列表
const articleList = ref([])

// 文章总数
const total = ref(0)

// 数据请求对象
const params = ref({
  pagenum: 1,
  pagesize: 5,
  cate_id: '',
  state: ''
})

// 表格加载状态
const isLoading = ref(true)

// 获取文章列表
const getArticleList = async () => {
  isLoading.value = true
  const res = await getArticleListAPI(params.value)
  console.log(res)
  res.data.data.forEach((item) => {
    item.pub_date = dayjs(item.pub_date).format('YYYY-MM-DD HH:mm:ss')
  })
  articleList.value = res.data.data
  total.value = res.data.total
  isLoading.value = false
}

// 搜索逻辑
const searchArticle = () => {
  // console.log(params.value)
  getArticleList(params.value)
}

// 重置搜索逻辑
const resetSearch = () => {
  params.value.cate_id = ''
  params.value.state = ''
  getArticleList()
}
// 初始化调用
onMounted(() => {
  getArticleList()
  getArticleCatagory()
})

// 弹框控制
const drawerVisible = ref(false)

// 添加文章
const addArticle = () => {
  drawerVisible.value = true
}

// 添加文章表单数据
const articleForm = ref({
  title: '',
  cate_id: '',
  content: '',
  cover_img: '',
  state: ''
})

// 文章分类数据
const categoryList = ref([])

// 获取文章分类
const getArticleCatagory = async () => {
  const res = await getArticleCatagoryAPI()
  categoryList.value = res.data.data
}

// 分页切换页数
const handleSizeChange = (value) => {
  // alert(value)
  params.value.pagesize = value
  getArticleList()
}

// 分页切换页码
const handleCurrentChange = (value) => {
  params.value.pagenum = value
  getArticleList()
}

// 文章表单对象
const articleRef = ref(null)

// 表单校验规则
const rules = {
  title: [
    { required: true, message: '请输入文章标题', trigger: 'blur' },
    { min: 2, max: 10, message: '文章标题长度为2-10个字符', trigger: 'blur' }
  ],
  cate_id: [{ required: true, message: '请选择文章分类', trigger: 'change' }],
  content: [{ required: true, message: '请输入文章内容', trigger: 'blur' }],
  cover_img: [{ required: true, message: '请上传文章封面', trigger: 'change' }]
}

// 图片选择
const onChange = (file) => {
  console.log(file.raw)
  articleForm.value.cover_img = file.raw
  // console.log(articleForm.value.cover_img);
}

// 发布逻辑
const addPublish = (state) => {
  articleRef.value.validate(async (valid) => {
    if (valid) {
      articleForm.value.state = state

      const params = new FormData()
      for (let key in articleForm.value) {
        params.append(key, articleForm.value[key])
      }

      if (drawerTitle.value === '发布文章') {
        // 发布文章
        const res = await addArticleAPI(params)
        console.log(res)
        if (res.status === 200) {
          ElMessage.success(res.data.message)

          drawerVisible.value = false
          getArticleList()
        }
      } else if (drawerTitle.value === '编辑文章') {
        // 编辑文章

        params.append('id', editId.value)
        const res = await editArticleAPI(params)
        console.log(res)
        if (res.status === 200) {
          ElMessage.success(res.data.message)
          console.log(res)
          drawerVisible.value = false
          getArticleList()
        }
      }
    }
  })
}

// 抽屉弹框标题状态
const drawerTitle = ref('发布文章')
// 编辑文章
const editArticle = async (id) => {
  // 获取文章详情
  // console.log(id);
  editId.value = Number(id)
  const res = await getArticleDetailAPI(id)
  // console.log(res)
  articleForm.value.title = res.data.data.title
  articleForm.value.cate_id = res.data.data.cate_id
  articleForm.value.content = res.data.data.content
  articleForm.value.state = res.data.data.state
  showImage.value =
    'http://big-event-vue-api-t.itheima.net' + res.data.data.cover_img
  articleForm.value.cover_img = await imageUrlToFile(
    showImage.value,
    res.data.data.cover_img
  )
  console.log(articleForm.value.cover_img)
  editId.value = res.data.data.id
  // 打开弹窗
  drawerVisible.value = true
  // 切换标题
  drawerTitle.value = '编辑文章'
}

// 关闭抽屉
const closeDrawer = () => {
  // 重置表单
  articleForm.value = {
    title: '',
    cate_id: '',
    content: '',
    cover_img: '',
    state: ''
  }
  showImage.value = ''
  articleRef.value.resetFields()
  editorRef.value.setHTML('')
  // 关闭弹窗
  drawerVisible.value = false
}

// 显示图片
const showImage = ref('')

// 编辑文章id
const editId = ref(0)

// 富文本编辑器组件
const editorRef = ref(null)

// 删除文章
const deleteArticle = async (id) => {
  ElMessageBox.confirm('您确定要删除该条文章吗？', '温馨提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  })
    .then(async () => {
      const res = await deleteArticleAPI(id)
      // console.log(res)
      if (res.status === 200) {
        ElMessage.success('删除成功')
        getArticleList()
      }
    })
    .catch(() => {})
}

// 图片链接转为file对象
async function imageUrlToFile(url, fileName) {
  try {
    // 第一步：使用axios获取网络图片数据
    const response = await axios.get(url, { responseType: 'arraybuffer' })
    const imageData = response.data

    // 第二步：将图片数据转换为Blob对象
    const blob = new Blob([imageData], {
      type: response.headers['content-type']
    })

    // 第三步：创建一个新的File对象
    const file = new File([blob], fileName, { type: blob.type })

    return file
  } catch (error) {
    console.error('将图片转换为File对象时发生错误:', error)
    throw error
  }
}
</script>

<template>
  <pageConrtainer style="width: 100%" title="文章管理">
    <template #extra>
      <el-button type="primary" @click="addArticle">添加文章</el-button>
    </template>
    <el-form inline>
      <el-form-item label="文章分类：">
        <selectCategory v-model="params.cate_id"></selectCategory>
      </el-form-item>
      <el-form-item label="发布状态：">
        <el-select v-model="params.state">
          <el-option label="已发布" value="已发布"></el-option>
          <el-option label="草稿" value="草稿"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="searchArticle">搜索</el-button>
        <el-button @click="resetSearch">重置</el-button>
      </el-form-item>
    </el-form>
    <el-table :data="articleList" v-loading="isLoading">
      <el-table-column label="文章标题" prop="title">
        <template v-slot="{ row }">
          <el-link type="primary" :underline="false">{{ row.title }}</el-link>
        </template>
      </el-table-column>
      <el-table-column label="分类" prop="cate_name"></el-table-column>
      <el-table-column label="发布时间" prop="pub_date"></el-table-column>
      <el-table-column label="发布状态" prop="state"></el-table-column>
      <el-table-column label="操作">
        <template v-slot="{ row }">
          <el-button
            type="primary"
            plain
            :icon="Edit"
            circle
            @click="editArticle(row.id)"
          ></el-button>
          <el-button
            type="danger"
            plain
            :icon="Delete"
            circle
            @click="deleteArticle(row.id)"
          >
          </el-button>
        </template>
      </el-table-column>
    </el-table>
    <el-pagination
      v-model:current-page="params.pagenum"
      v-model:page-size="params.pagesize"
      :page-sizes="[3, 5, 10, 20]"
      :background="background"
      layout=" prev, pager, next, jumper,->, sizes,total"
      :total="total"
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
      style="margin-top: 30px"
    />
    <el-drawer
      v-model="drawerVisible"
      :title="drawerTitle"
      direction="rtl"
      size="50%"
      @close="closeDrawer"
    >
      <el-form
        ref="articleRef"
        :model="articleForm"
        :rules="rules"
        label-width="100px"
      >
        <el-form-item label="文章标题" prop="title">
          <el-input v-model="articleForm.title"></el-input>
        </el-form-item>
        <el-form-item label="文章分类" prop="cate_id">
          <el-select v-model="articleForm.cate_id" style="width: 100%">
            <el-option
              v-for="item in categoryList"
              :key="item.id"
              :value="item.id"
              :label="item.cate_name"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="文章封面" prop="cover_img"
          ><Upload @change="onChange" :img="showImage"></Upload
        ></el-form-item>
        <el-form-item label="文章内容" prop="content">
          <div class="editor">
            <QuillEditor
              them="snow"
              v-model:content="articleForm.content"
              content-type="html"
              ref="editorRef"
            ></QuillEditor>
          </div>
        </el-form-item>
        <el-form-item>
          <el-button @click="addPublish('已发布')" type="primary"
            >发布</el-button
          >
          <el-button @click="addPublish('草稿')" type="info">草稿</el-button>
        </el-form-item>
      </el-form>
    </el-drawer>
  </pageConrtainer>
</template>

<style scoped lang="scss">
.editor {
  width: 100%;
  :deep(.ql-editor) {
    min-height: 200px;
  }
}
</style>
